package org.lib.mysqlhello.user.controller;

import java.util.Objects;
import java.util.Optional;

import org.lib.mysqlhello.common.ResultVO;
import org.lib.mysqlhello.user.controller.dto.AddUserDTO;
import org.lib.mysqlhello.user.controller.dto.UpdateUserDTO;
import org.lib.mysqlhello.user.entity.User;
import org.lib.mysqlhello.user.repository.UserCrudRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

/**
 * User接口
 * @author ben
 * @date 2021-08-21 23:10:07 CST
 */
@RestController
@RequestMapping(value="user")
@Slf4j
public class UserController implements UserCrudFacade {

	@Autowired
	private UserCrudRepository userCrudRepository;
	
	/**
	 * 添加成功，返回User.id
	 */
	@Override
	public ResultVO<Long> addUser(@RequestBody AddUserDTO dto) {
		User user = new User(dto.getFirstName(), dto.getLastName(), dto.getAge());
		userCrudRepository.save(user);
		log.info("saved user={}", user);
		if (Objects.isNull(user.getId())) {
			return ResultVO.getFailed(500, "添加失败", null);
		} else {
			return ResultVO.getSuccess(user.getId());
		}
	}

	/**
	 * 删除成功，返回data为false
	 */
	@Override
	public ResultVO<Boolean> delUser(@RequestParam Long id) {
		// 临时：后改为 入参校验
		Objects.requireNonNull(id);
		
		if (userCrudRepository.existsById(id)) {
			// 存在才删除
			userCrudRepository.deleteById(id);
		}
		
		return ResultVO.getSuccess(userCrudRepository.existsById(id));
	}

	@Override
	public ResultVO<Boolean> updateUser(@RequestBody UpdateUserDTO dto) {
		Long id = dto.getId();
		if (Objects.isNull(id)) {
			// 400 客户端错误
			return ResultVO.getFailed(400, "id不能为null", null);
		}
		
		Optional<User> opuser = userCrudRepository.findById(id);
		if (!opuser.isPresent()) {
			return ResultVO.getFailed(400, "用户不存在", null);
		}
		
		User user = opuser.get();
		
		StringBuffer sb = new StringBuffer();
		boolean needUpdate = false;
		if (StringUtils.hasText(dto.getFirstName()) && !user.getFirstName().equals(dto.getFirstName())) {
			sb.append("更新firstName;");
			user.setFirstName(dto.getFirstName());
			needUpdate = true;
		}
		if (StringUtils.hasText(dto.getLastName()) && !user.getLastName().equals(dto.getLastName())) {
			sb.append("更新lastName;");
			user.setLastName(dto.getLastName());
			needUpdate = true;
		}
		if (!Objects.isNull(dto.getAge()) && !dto.getAge().equals(user.getAge())) {
			sb.append("更新age;");
			user.setAge(dto.getAge());
			needUpdate = true;
		}
		if (needUpdate) {
			log.info("更新User：id={}, 更新项={}", sb);
			User updatedUser = userCrudRepository.save(user);
			log.info("update updatedUser={}", updatedUser);
			//  这里的findById获取的数据的 updateTime 不是最新的,TODO
			log.info("update 2 updatedUser={}", userCrudRepository.findById(id).get());
			// 还需判断
			return ResultVO.getSuccess(true);
		} else {
			// 无需更新
			return ResultVO.getFailed(400, "无需更新", false);
		}
	}

	/**
	 * 查询失败，返回data=null
	 */
	@Override
	public ResultVO<User> getUserById(@RequestParam Long id) {
		// 临时：后改为 入参校验
		Objects.requireNonNull(id);
		
		User fuser = null;
		
		Optional<User> opu = userCrudRepository.findById(id);
		if (opu.isPresent()) {
			fuser = opu.get();
		}
		
		return ResultVO.getSuccess(fuser);
	}
	
}
